package com.saibo.spider.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

public class HttpResponseUtil {
	public static String getHtml(CloseableHttpResponse httpResponse) {
		if(null==httpResponse) return null;
		try {
			String line = null;
			String html = "";
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpResponse.getEntity();
				InputStream in = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					html = html + line;
				}
			} else {
				return null;
			}
			return html;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getHtml(CloseableHttpResponse httpResponse, String encode) {
		String line = null;
		String html = "";
		try {
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpResponse.getEntity();
				InputStream in;
				in = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in, encode));
				while ((line = reader.readLine()) != null) {
					html = html + line;
				}
			} else {
				return null;
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return html;
	}
}
